package com.smart.util;

import java.util.Date;

import net.sf.json.JSONObject;

import com.smart.constants.SmartConstants;
import com.smart.model.AccessToken;
import com.smart.model.JSApiTicket;

public class JSApiTicketManager {
	  private static JSApiTicket jsApiTicket;
	  private static long getTime;
	  public static boolean isExpired()
	  {
		  Date d=new Date();
		  //计算当前到现在经过了多少秒
		  long interval=(d.getTime()-getTime)/1000;
		  if(interval>jsApiTicket.getExpires_in()-3) //之所以减去3秒，是考虑程序等会执行时AccessToken可能会过期
	             return true;
		  else return false;
	  }
	  public static JSApiTicket getJSApiTicket()
	  {
		  System.out.println("开始获取jsApiTicket");
		  if(jsApiTicket==null||isExpired())
		  {
			  //如果JSApiTicket为空，则必须先初始化JSApiTicket
			  if(jsApiTicket==null)   jsApiTicket=new JSApiTicket();
			  AccessToken accessToken=AccessTokenManager.getAccessToken();
			  String url=SmartConstants.ACCESSTOKEN_FOR_JSTICKET.replace("ACCESS_TOKEN",accessToken.getToken());
			  JSONObject jsonObject=WeixinUtil.doGetStr(url);
			  if(jsonObject!=null)
			  {
				  System.out.println("获取jsApiTicket成功");
				  System.out.println(jsonObject);
				  jsApiTicket.setTicket(jsonObject.getString("ticket"));
				  jsApiTicket.setExpires_in(jsonObject.getInt("expires_in"));
				  getTime=new Date().getTime();
			  }
			  else
			  {
				  System.out.println("获取jsApiTicket失败");
			  }
		  }
		  return jsApiTicket;
	  }
	  
	  public static void main(String[] args)
	  {
		  JSApiTicket jsApiTicket=getJSApiTicket();
		  System.out.println("ticket:"+jsApiTicket.getTicket());
		  System.out.println("expires_in:"+jsApiTicket.getExpires_in());
	  }
}
